<template>
  <div :class="{'inline': inline}">
    <el-upload
      ref="upload"
      v-bind="$attrs"
      :action="action"
      :on-success="handleSuccess"
      :on-error="handleError" 
      :limit="limit"
      :before-upload="beforeUpload"
      :show-file-list="showFileList" 
      :accept="accept" 
      v-on="$listeners">
      <slot>
        <el-button type="search" :loading="loading">上传文件</el-button>
      </slot>
    </el-upload>
  </div>
</template>

<script>
export default {
  props: {
    action: {
      type: String,
      default: '/api/api/general/upload_file'
    },
    showFileList: {
      type: Boolean,
      default() {
        return false
      }
    },
    limit: {
      type: Number,
      default() {
        return 1
      }
    },
    accept: {
      type: String,
      default: '.pdf,.doc,.docx,.xls,.xlsx'
    },
    fileList: {
      type: Array,
      default() {
        return []
      }
    },
    inline: [String, Boolean],
    fileMaxSize: {
      type: Number,
      default() {
        return 20480000
      }
    }
  },
  data() {
    return {
      files: this.fileList,
      loading: false
    }
  },
  beforeDestroy() {
    this.$refs.upload.clearFiles()
  },
  watch: {
    fileList(array) {
      this.files = array
    }
  },
  computed: {
    accepts() {
      return this.accept.replace(/\./g, '').split(',')
    }
  },
  methods: {
    handleSuccess (response) {
      this.files.push(response.data.filePathNameHttp)
      this.$emit('update:fileList', this.files)
      this.$emit('success', response)
      this.$refs.upload.clearFiles()
      this.loading = false
    },
    beforeUpload(file){
      if (file.size > this.fileMaxSize) {
        this.$message.error("上传文件过大，只能上传小于20M的文件")
        return false
      }
      this.loading = true
      let i = file.name.lastIndexOf('.')
      let ext = file.name.slice(i+1)
      if(!this.accepts.includes(ext)){
        this.$message.error("仅支持" + this.accept + "后缀文件")
        return false
      }
    },
    handleError(){
      this.$message.error('上传失败')   
      this.loading = false
    }
  }
}
</script>

<style>
  .inline {
    display: inline-block;
  }
</style>
